package orders

import (
	"context"
	"errors"
	"github.com/google/uuid"
	"github.com/kuangshp/go-utils/k"
	"github.com/shopspring/decimal"
	"gorm.io/gorm"
	"insighttracking/common/utils"
	"insighttracking/query/service"
	"net/http"

	"insighttracking/apps/sorting/internal/svc"
	"insighttracking/apps/sorting/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
	"os"
)

type GetOrdersDetailApiLogic struct {
	logx.Logger
	ctx     context.Context
	svcCtx  *svc.ServiceContext
	Request *http.Request
}

func NewGetOrdersDetailApiLogic(ctx context.Context, svcCtx *svc.ServiceContext, request *http.Request) *GetOrdersDetailApiLogic {
	hostname, _ := os.Hostname()
	return &GetOrdersDetailApiLogic{
		Logger: logx.WithContext(ctx).WithCallerSkip(0).WithFields(
			logx.Field("Log_UUID", uuid.New().String()),
			logx.Field("hostname", hostname)),
		ctx:     ctx,
		svcCtx:  svcCtx,
		Request: request,
	}
}

func (l *GetOrdersDetailApiLogic) GetOrdersDetailApi(req *types.IdReq) (resp *types.OrdersResp, err error) {
	resp = &types.OrdersResp{}
	ordersBo, err := service.OrdersService.GetDetailByIdApi(l.ctx, req.Id)
	if err != nil {
		return nil, errors.New("传递的主键错误")
	}

	spuMap, err := service.OrdersDetailService.GetTotalSpuApi(l.ctx, []int64{req.Id})
	if err != nil {
		return
	}
	var detailList = make([]types.OrdersDetailResp, 0)
	for _, spu := range spuMap {
		storeSortingDetailList, err2 := service.StoreSortingDetailService.GetStoreSortingDetailBySpuIDApi(l.ctx, req.Id, spu.SpuID)
		completeCount := decimal.Zero
		var status int64
		if err2 == nil && len(storeSortingDetailList) > 0 {
			for _, item3 := range storeSortingDetailList {
				completeCount = completeCount.Add(item3.OutboundCount)
			}
			status = 10
		}
		// 查询是否有出库记录
		sendGoodsRecordEntity, err2 := service.SendGoodsRecordService.GetStoreSortingByOrderIdApi(l.ctx, req.Id)
		if !errors.Is(err2, gorm.ErrRecordNotFound) {
			_, err = service.SendGoodsRecordDetailService.GetSendGoodsRecordDetailBySpuIdApi(l.ctx, sendGoodsRecordEntity.ID, spu.SpuID)
			l.Logger.Infof("当前出库记录:%+v", sendGoodsRecordEntity)
			if !errors.Is(err, gorm.ErrRecordNotFound) {
				status = 20
			}
		}
		spuEntity, err := service.SpuService.GetBySpuIdApi(l.ctx, spu.SpuID)
		if err != nil {
			return resp, err
		}
		detailList = append(detailList, types.OrdersDetailResp{
			ID:                      spu.SpuID,                                          // 主键id
			SpuID:                   spu.SpuID,                                          // 商品id,关联到spu表主键id
			SpuCount:                spu.Count.StringFixed(2),                           // 商品数量
			SnapshotPrice:           spuEntity.SalesPrice.StringFixed(2),                // 快照单价
			SpuAmount:               spuEntity.SalesPrice.Mul(spu.Count).StringFixed(2), // 商品金额小计
			SnapshotName:            spuEntity.Name,                                     // 快照商品名称
			SnapshotProductImageURL: spuEntity.ProductImageURL,                          // 快照产品图片
			SnapshotCategory:        spuEntity.CategoryName,                             // 快照分类
			SnapshotUnit:            spu.UnitName,                                       // 快照单位
			SnapshotSpuType:         spuEntity.SpuType,                                  // 快照商品类型,0表示基础商品,1表示加工商品
			SnapshotBrand:           "",                                                 // 快照品牌
			SnapshotSupplier:        "",                                                 // 快照供应商
			Remark:                  "",                                                 // 备注
			CreatedAt:               utils.TimestampToString(ordersBo.CreatedAt),        // 创建时间
			UpdatedAt:               utils.TimestampToString(ordersBo.UpdatedAt),        // 更新时间
			CompleteCount:           completeCount.StringFixed(2),                       // 完成分拣重量
			Status:                  status,                                             // 状态,0表示待分拣,10表示已分拣，20表示已出库
		})
	}
	// 查询订单详情
	//detailEntities, err := service.OrdersDetailService.GetByOrderIdListApi(l.ctx, []int64{req.Id})
	//var detailList = make([]types.OrdersDetailResp, 0)
	//if err == nil && len(detailEntities) > 0 {
	//	detailList = k.Map(detailEntities, func(item *model.OrdersDetailEntity, index int) types.OrdersDetailResp {
	//		storeSortingDetailList, err2 := service.StoreSortingDetailService.GetStoreSortingDetailByOrdersDetailIdsApi(l.ctx, item.ID)
	//		completeCount := decimal.Zero
	//		var status int64
	//		if err2 == nil && len(storeSortingDetailList) > 0 {
	//			for _, item3 := range storeSortingDetailList {
	//				completeCount = completeCount.Add(item3.OutboundCount)
	//			}
	//			status = 10
	//		}
	//		// 查询是否有出库记录
	//		sendGoodsRecordEntity, err2 := service.SendGoodsRecordService.GetStoreSortingByOrderIdApi(l.ctx, item.OrdersID)
	//		if !errors.Is(err2, gorm.ErrRecordNotFound) {
	//			_, err = service.SendGoodsRecordDetailService.GetSendGoodsRecordDetailBySpuIdApi(l.ctx, sendGoodsRecordEntity.ID, item.SpuID)
	//			l.Logger.Infof("当前出库记录:%+v", sendGoodsRecordEntity)
	//			if !errors.Is(err, gorm.ErrRecordNotFound) {
	//				status = 20
	//			}
	//		}
	//		return types.OrdersDetailResp{
	//			ID:                      item.ID,                                 // 主键id
	//			SpuID:                   item.SpuID,                              // 商品id,关联到spu表主键id
	//			SpuCount:                item.SpuCount.StringFixed(2),            // 商品数量
	//			SnapshotPrice:           item.SnapshotPrice.StringFixed(2),       // 快照单价
	//			SpuAmount:               item.SpuAmount.StringFixed(2),           // 商品金额小计
	//			SnapshotName:            item.SnapshotName,                       // 快照商品名称
	//			SnapshotProductImageURL: item.SnapshotProductImageURL,            // 快照产品图片
	//			SnapshotCategory:        item.SnapshotCategory,                   // 快照分类
	//			SnapshotUnit:            item.SnapshotUnit,                       // 快照单位
	//			SnapshotSpuType:         item.SnapshotSpuType,                    // 快照商品类型,0表示基础商品,1表示加工商品
	//			SnapshotBrand:           item.SnapshotBrand,                      // 快照品牌
	//			SnapshotSupplier:        item.SnapshotSupplier,                   // 快照供应商
	//			Remark:                  item.Remark,                             // 备注
	//			CreatedAt:               utils.TimestampToString(item.CreatedAt), // 创建时间
	//			UpdatedAt:               utils.TimestampToString(item.UpdatedAt), // 更新时间
	//			CompleteCount:           completeCount.StringFixed(2),            // 完成分拣重量
	//			Status:                  status,                                  // 状态,0表示待分拣,10表示已分拣，20表示已出库
	//		}
	//	})
	//}
	return &types.OrdersResp{
		ID:                 ordersBo.ID,                                                                               // 主键id
		OrderNo:            ordersBo.OrderNo,                                                                          // 订单流水号
		EnterpriseID:       ordersBo.EnterpriseID,                                                                     // 关联到enterprise表主键id
		CustomerID:         ordersBo.CustomerID,                                                                       // 客户id,关联到enterprise_customer表主键id
		CustomerName:       ordersBo.CustomerName,                                                                     // 门店名称
		SendGoodsDate:      k.If(ordersBo.SendGoodsDate.IsZero(), 0, utils.TimestampToString(ordersBo.SendGoodsDate)), // 发货日期
		SendGoodsMethod:    ordersBo.SendGoodsMethod,                                                                  // 发货方式,0表示司机配送
		SettlementMethod:   ordersBo.SettlementMethod,                                                                 // 结算方式，0表示账期
		PurchaserID:        ordersBo.PurchaserID,                                                                      // 采购员,关联到
		PurchaserName:      ordersBo.PurchaserName,                                                                    // 采购员名称
		Remark:             ordersBo.Remark,                                                                           // 订单备注
		TotalAmount:        ordersBo.TotalAmount.StringFixed(2),                                                       // 订单金额
		TotalCount:         ordersBo.TotalCount.StringFixed(2),                                                        // 订单商品数量
		Status:             ordersBo.Status,                                                                           // 订单状态,0表示已下单(待采购),1表示采购中,2表示已采购,3待入库，4已入库，5已发货,6已收货,7表示退货
		ReceiveGoodsName:   ordersBo.ReceiveGoodsName,                                                                 // 收货员姓名
		ReceiveGoodsMobile: ordersBo.ReceiveGoodsMobile,                                                               // 收货人手机号码
		ReceiveAddress:     ordersBo.ReceiveAddress,                                                                   // 收货人地址
		IsPurchasingPlan:   ordersBo.IsPurchasingPlan,                                                                 // 是否发布采购计划,0表示不发布,1表示发布
		Source:             ordersBo.Source,                                                                           // 订单来源,0表示app端,1表示pc下单
		SettlementStatus:   ordersBo.SettlementStatus,                                                                 // 结算状态，0表示未结算,1表示已结算
		SendGoodsID:        ordersBo.SendGoodsID,                                                                      // 配置司机,关联到account表主键id
		SendGoodsName:      ordersBo.SendGoodsName,                                                                    // 配送司机名称
		WarehouseID:        ordersBo.WarehouseID,                                                                      // 发货仓库,关联到warehouse表主键id
		WarehouseName:      ordersBo.WarehouseName,                                                                    // 仓库名称
		CreatedAt:          utils.TimestampToString(ordersBo.CreatedAt),                                               // 创建时间
		UpdatedAt:          utils.TimestampToString(ordersBo.UpdatedAt),                                               // 更新时间
		DetailList:         detailList,                                                                                // 商品详情
	}, nil
}
